import React, { useEffect, useState } from 'react';
import { Card, Upload, Table, Button, message, Popconfirm } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';
import styles from './index.module.css';
import { fileAPI, FileInfo } from '@/services/file';

const FilePage: React.FC = () => {
  const [files, setFiles] = useState<FileInfo[]>([]);
  const [loading, setLoading] = useState(false);

  const fetchFiles = async () => {
    setLoading(true);
    try {
      const files = await fileAPI.getList();
      setFiles(files || []);  // 直接使用返回的数组
    } catch (error) {
      console.error('获取文件列表失败:', error);
      message.error('获取文件列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await fileAPI.delete(id);
      message.success('删除成功');
      fetchFiles();
    } catch (error) {
      console.error('删除文件失败:', error);
      message.error('删除失败');
    }
  };

  const uploadProps: UploadProps = {
    name: 'file',
    multiple: false,
    showUploadList: false,  // 修改这里，不显示上传列表
    customRequest: async (options) => {
      const { file, onSuccess, onError, onProgress } = options;
      try {
        onProgress?.({ percent: 50 });
        
        const response = await fileAPI.upload(file as File);
        console.log('上传响应:', response);
        
        if (response) {
          onProgress?.({ percent: 100 });
          onSuccess?.(response);
          message.success('文件上传成功');
          await fetchFiles();
        } else {
          throw new Error('上传响应无效');
        }
      } catch (error: any) {
        console.error('文件上传失败:', error);
        onError?.(error);
        message.error(error.message || '文件上传失败');
      }
    }
  };

  const columns = [
    {
      title: '文件名',
      dataIndex: 'filename',
      key: 'filename',
    },
    {
      title: '大小',
      dataIndex: 'file_size',
      key: 'file_size',
      render: (size: number) => {
        const kb = size / 1024;
        if (kb < 1024) {
          return `${kb.toFixed(2)} KB`;
        }
        return `${(kb / 1024).toFixed(2)} MB`;
      },
    },
    {
      title: '上传时间',
      dataIndex: 'upload_time',
      key: 'upload_time',
      render: (time: string) => new Date(time).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: FileInfo) => (
        <Popconfirm
          title="确定要删除这个文件吗？"
          onConfirm={() => handleDelete(record.id)}
        >
          <Button type="link" danger>
            删除
          </Button>
        </Popconfirm>
      ),
    },
  ];

  useEffect(() => {
    fetchFiles();
  }, []);

  return (
    <div className={styles.container}>
      <Card>
        <Upload {...uploadProps}>
          <Button icon={<UploadOutlined />}>点击上传</Button>
        </Upload>
        <Table
          style={{ marginTop: 16 }}
          columns={columns}
          dataSource={files}
          loading={loading}
          rowKey="id"
        />
      </Card>
    </div>
  );
};

export default FilePage;